var apiHost = wx.getStorageSync('apiHost');
var yunId = wx.getStorageSync('yunId');

var Appid = wx.getStorageSync('Appid');
var Secret = wx.getStorageSync('Secret');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo : '',
    showCancelArea: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var openId = wx.getStorageSync('openId');     //用户openId获取
    var phone = wx.getStorageSync('phone');       //用户phone获取
    var userId = wx.getStorageSync('userId');     //用户userId获取
    var userInfo = wx.getStorageSync('userInfo'); //用户userInfo获取

    if (openId != '') {
      that.setData({
        openId: openId,
        showCancelArea: false
      });
    } else {
      that.setData({
        showCancelArea: true
      });
    }

    /**
     * 判断是否有手机号
     */
    if (phone == '') {
      that.setData({
        phone: ''
      })
    } else {
      that.setData({
        phone: phone
      })
    }

    if (userId != '') {
      that.setData({
        userId: userId
      });
    }

    if (userInfo != '') {
      that.setData({
        userInfo: userInfo
      });
    }

    that.shopDetail();

  },

  /**
  * 手机号授权方式
  */
  getPhoneNumberF: function (res) {
    var that = this;
    var errMsgFlg = res.detail.errMsg

    if ("getPhoneNumber:ok" == errMsgFlg) {
      var userCon = res.detail
      wx.login({
        success: function (r) {
          var code = r.code;//登录凭证
          if (code) {
            that.VERBurl(userCon, code)
            wx.showToast({
              title: '登录成功',
              icon: 'none',
              duration: 2000,
              mask: true
            });
          } else {
            wx.showToast({
              title: '获取用户登录态失败！' + r.errMsg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        },
        fail: function () {

          wx.showToast({
            title: '登陆失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    } else {
      wx.showToast({
        title: '请授权',
        icon: 'none',
        duration: 2000,
        mask: true
      });
    }
  },
  /**
   * 解密用户登录完成后的url (用户手机号)
   */
  VERBurl: function (res, code) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息  (注意：这个东西必须需要 开放平台 授权)
    wx.request({
      url: apiHost + 'xcx/UserInfo/decodePhoneNumber',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        code: code,
        Appid: Appid,
        Secret: Secret
      },
      success: function (data) {
        //4.解密成功后 获取自己服务器返回的结果
        if (data.data.status == 1) {
          var phone = data.data.userInfo.phoneNumber;
          wx.setStorageSync('phone', phone);

          that.setData({
            phone: phone
          })
          that.reginPhoneOpenid(phone);
        } else {
          that.setData({
            phone: ''
          })
          wx.showToast({
            title: '解密失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {

        wx.showToast({
          title: '系统错误',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },
  //表单提交
  reginPhoneOpenid: function (userPhone) {
    var that = this;

    var nickName = that.data.userInfo.nickName;     //	昵称
    var avatarUrl = that.data.userInfo.avatarUrl;   //用户头像
    var gender = that.data.userInfo.gender;         //性别1为男，0为女
    var city = that.data.userInfo.city;             //城市
    var country = that.data.userInfo.country;       //国家
    var province = that.data.userInfo.province;     //省

    wx.request({
      url: apiHost + "xcx/login/reg",
      data: {
        // openId: 'olGet4mNKn1FeKEvSrGiMuY6v3ZB',
        openId: that.data.openId,
        yunId: yunId,
        userPhone: userPhone,
        nickName: nickName,
        avatarUrl: avatarUrl,
        gender: gender,
        city: city,
        country: country,
        province: province
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.code == '10004') {
          that.setData({
            is_code: true,        //提示信息
            ts_msg: res.data.msg
          })
        }
        if (res.data.code == '10000') {
          that.setData({
            is_code: true,        //提示信息
            ts_msg: '　'
          })
        } else {
          that.setData({
            is_code: (!that.data.is_phone),   //提示信息
            ts_msg: res.data.msg
          })
        }
      },
    });

  },
  
  //跳转登录
  login: function () {
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true
    })
    wx.navigateTo({
      url: '../login/login'
    });
  },

  //跳转登录
  toYunShopIndex: function () {
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true
    })
    wx.navigateTo({
      url: '../yunShopIndex/yunShopIndex'
    });
  },


  //跳转我的订单
  orderList: function () {
    var that = this;
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true
    })
    wx.navigateTo({
      url: '../userOrder/userOrderList/userOrderList?yunId=' + yunId + '&openId=' + that.data.openId
    });
  },
  //跳转到关于我们
  aboutUs:function(){
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true
    })
    wx.navigateTo({
      url: '../aboutUs/aboutUs'
    });
  },

  contactShop : function(){
    var that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.shopDetailCon.phone //仅为示例，并非真实的电话号码 
    })
  },
  //商家详情
  shopDetail: function () {
    var that = this;
    //商家
    wx.request({
      url: apiHost + "/xcx/store/detail",
      data: {
        yunId: yunId,
        userId: that.data.userId
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        if (code=="10000"){
          that.setData({
            shopDetailCon: res.data.data
          })
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        
      }
    })
  },

  /**
   * 获取用户手机号回调方法
   */
  getPhoneNumberMyshop: function (res){
    var that = this;
    var errMsgFlg = res.detail.errMsg

    if ("getPhoneNumber:ok" == errMsgFlg) {
      var userCon = res.detail
      wx.login({
        success: function (r) {
          var code = r.code;//登录凭证
          if (code) {
            that.VERBurl(userCon, code)
          } else {
            wx.showToast({
              title: '获取用户登录态失败！' + r.errMsg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        },
        fail: function () {

          wx.showToast({
            title: '登陆失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    }
  },

  /**
  * 解密用户登录完成后的url (用户手机号)
  */
  VERBurl: function (res, code) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息  (注意：这个东西必须需要 开放平台 授权)
    wx.request({
      url: apiHost + 'xcx/UserInfo/decodePhoneNumber',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        code: code,
        Appid: 'wx910d63f3cec2d59b',
        Secret: '3f8216c7ada3554a4701e67e729b839b'
      },
      success: function (data) {
        //4.解密成功后 获取自己服务器返回的结果
        if (data.data.status == 1) {
          var phone = data.data.userInfo.phoneNumber;

          wx.setStorageSync('phone', phone);

          that.setData({
            phone: phone
          })
          that.myshopPd(phone);
        } else {
          wx.showToast({
            title: '解密失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {

        wx.showToast({
          title: '系统错误',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  myshopPd: function (phone){
    var that = this;
    //商家
    wx.request({
      url: apiHost + "/xcx/store/bindOpenId",
      data: {
        openId: that.data.openId,
        yunId: yunId,
        phone: phone
      },
      header: {
        "Content-Type": "application/json"
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        var flag = res.data.data;

        console.log(res)
        if (code == "10000") {
          that.toYunShopIndex();//跳转商家
        } else {
          wx.showModal({
            title: '商家登录失败',
            content: '您目前还不是商家！如有疑问请联系我们。微信：15522952750eee，电话：15522952750',
            showCancel :false,
            confirmColor : '#ff2040',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }

      }
    })
  },

  /**
   * 切换商家
   */
  myShopFlag: function (res){
    var that = this;

    var phone = res.currentTarget.dataset.toggle;


    that.myshopPd(phone)
  },
  //按钮获取用户信息
  getUserInfo: function (res) {
    var that = this;

    var errMsgFlg = res.detail.errMsg

    if ("getUserInfo:ok" == errMsgFlg) {
      var userCon = res.detail
      wx.login({
        success: function (r) {
          var code = r.code;//登录凭证
          if (code) {
            that.VERBurlUser(userCon, code)
          } else {
            wx.showToast({
              title: '获取用户登录态失败！' + r.errMsg,
              icon: 'none',
              duration: 2000,
              mask: true
            });
          }
        },
        fail: function () {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '登陆失败',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    }
  },

  /**
  * 解密用户登录完成后的url
  */
  VERBurlUser: function (res, code) {
    var that = this;
    wx.showLoading({
      title: '加载中',
      icon: 'loading',
    });
    //3.请求自己的服务器，解密用户信息 获取unionId等加密信息  (注意：这个东西必须需要 开放平台 授权)
    wx.request({
      url: apiHost + 'xcx/UserInfo/decodeUserInfo',//自己的服务接口地址
      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        encryptedData: res.encryptedData,
        iv: res.iv,
        code: code,
        Appid: Appid,
        Secret: Secret
      },
      success: function (data) {
        //4.解密成功后 获取自己服务器返回的结果
        if (data.data.status == 1) {
          var userInfo_ = data.data.userInfo;

          var openIdFl = userInfo_.openId;
          var phone = userInfo_.phone;

          wx.setStorageSync('userId', userInfo_.unionId);
          wx.setStorageSync('openId', openIdFl);
          wx.setStorageSync('phone', phone);
          wx.setStorageSync('session_token', userInfo_.session_key);
          wx.setStorageSync('userInfo', userInfo_);

          that.setData({
            showCancelArea: false
          });
          that.onLoad();
        } else {
          wx.hideLoading();   //隐藏加载loading
          wx.showToast({
            title: '网络异常',
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }

        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {
        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000,
          mask: true
        });
        wx.hideLoading();   //隐藏加载loading
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var openIdFlag = wx.getStorageSync('openId');     //用户openId获取
    var phoneFlag = wx.getStorageSync('phone');       //用户phone获取
    //判断openId是否存在
    if (openIdFlag != '') {
      that.setData({
        openId: openIdFlag,
        showCancelArea: false
      });
    } else {
      that.setData({
        showCancelArea: true
      });
    }
    //判断手机号是否存在
    if (phoneFlag != '') {
      that.setData({
        phone: phoneFlag
      });
    } else {
      that.setData({
        phone: ''
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },
})